<template>
  <div class="main-container">
    <!-- 左侧地图区域 -->
    <div class="map-section">
      <MapContainer ref="mapContainer" />
    </div>

    <!-- 右侧控制面板 -->
    <div class="control-panel">
      <div class="panel-header">
        <h2>地图控制面板</h2>
      </div>

      <div class="panel-content">
        <!-- 起点设置功能 -->
        <div class="control-group">
          <h3>起点设置</h3>
          <div class="point-actions">
            <el-button
                type="primary"
                @click="setStartByClick"
                plain
            >
              点击地图设起点
            </el-button>
            <el-button
                type="danger"
                @click="clearStartMarker"
                plain
                style="margin-left: 10px;"
            >
              清除起点
            </el-button>
          </div>

          <!-- 起点信息显示 -->
          <div class="point-info" v-if="startPointInfo">
            <p><strong>起点坐标:</strong></p>
            <p>经度: {{ startPointInfo.lng }}</p>
            <p>纬度: {{ startPointInfo.lat }}</p>
            <p v-if="startPointInfo.address"><strong>地址:</strong> {{ startPointInfo.address }}</p>
          </div>
        </div>

        <!-- 目的地设置功能 -->
        <div class="control-group">
          <h3>目的地设置</h3>
          <div class="point-actions">
            <el-button
                type="warning"
                @click="setDestinationByClick"
                plain
            >
              点击地图设目的地
            </el-button>
            <el-button
                type="danger"
                @click="clearDestinationMarker"
                plain
                style="margin-left: 10px;"
            >
              清除目的地
            </el-button>
          </div>

          <!-- 目的地信息显示 -->
          <div class="point-info" v-if="destinationPointInfo">
            <p><strong>目的地坐标:</strong></p>
            <p>经度: {{ destinationPointInfo.lng }}</p>
            <p>纬度: {{ destinationPointInfo.lat }}</p>
            <p v-if="destinationPointInfo.address"><strong>地址:</strong> {{ destinationPointInfo.address }}</p>
          </div>
        </div>

        <!-- 路线信息显示 -->
        <div class="control-group" v-if="routeInfo">
          <h3>路线信息</h3>
          <div class="route-info">
            <p><strong>距离:</strong> {{ routeInfo.distance }}公里</p>
            <p><strong>预计时间:</strong> {{ routeInfo.time }}分钟</p>
            <p><strong>预估费用:</strong> {{ routeInfo.price }}元</p>
          </div>
        </div>

        <!-- 轨迹动画按钮 -->
        <div class="control-group" v-if="startPointInfo && destinationPointInfo">
          <el-button
              type="success"
              @click="showTrackAnimation"
              plain
              style="width: 100%;"
              :loading="isAnimating"
          >
            立即打车
          </el-button>
        </div>

        <!-- 搜索功能 -->
        <div class="control-group">
          <h3>地点搜索</h3>
          <div class="input-group">
            <el-input
                v-model="searchKeyword"
                placeholder="请输入地点名称"
                clearable
                @keyup.enter="searchPlace"
            >
              <template #prepend>搜索</template>
            </el-input>
            <el-button type="primary" @click="searchPlace" :loading="searching">
              搜索
            </el-button>
          </div>
        </div>

        <!-- 清除所有标记 -->
        <div class="control-group">
          <el-button
              type="danger"
              @click="clearAllMarkers"
              plain
              style="width: 100%;"
          >
            清除所有标记
          </el-button>
        </div>

        <!-- 搜索结果列表 -->
        <div class="control-group" v-if="poiList.length > 0">
          <h3>搜索结果列表</h3>
          <div class="poi-list">
            <div
                v-for="(poi, index) in poiList"
                :key="index"
                class="poi-item"
                @click="selectPoi(poi)"
            >
              <div class="poi-name">{{ poi.name }}</div>
              <div class="poi-address">{{ poi.address || '地址未知' }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage, ElLoading} from 'element-plus'
import MapContainer from './MapContainer.vue'
import {useRouter} from 'vue-router'

// 响应式数据
const searchKeyword = ref('')
const poiList = ref([])
const searching = ref(false)
const startPointInfo = ref(null) // 起点信息
const destinationPointInfo = ref(null) // 目的地信息
const isAnimating = ref(false) // 是否正在播放动画
const routeInfo = ref(null) // 路线信息

// 地图相关引用
const mapContainer = ref(null)
const router = useRouter()
let map = null
let placeSearch = null
let geocoder = null
let isSettingStart = false; // 是否正在设置起点
let isSettingDestination = false; // 是否正在设置目的地

// 等待地图加载完成
const waitForMap = () => {
  return new Promise((resolve) => {
    const checkMap = () => {
      if (mapContainer.value && mapContainer.value.getMap()) {
        resolve(mapContainer.value.getMap())
      } else {
        setTimeout(checkMap, 100)
      }
    }
    checkMap()
  })
}

// 初始化地图插件
const initMapPlugins = async () => {
  try {
    map = await waitForMap()

    // 绑定地图点击事件
    map.on('click', handleMapClick)
    map.on('rightclick', handleMapRightClick)

    // 加载地理编码插件
    window.AMap.plugin(['AMap.Geocoder'], () => {
      geocoder = new window.AMap.Geocoder({
        city: '全国'
      })
      console.log('Geocoder插件加载成功')
    })

    // 加载POI搜索插件
    window.AMap.plugin(['AMap.PlaceSearch'], () => {
      placeSearch = new window.AMap.PlaceSearch({
        pageSize: 10,
        pageIndex: 1,
        city: '全国'
      })
      console.log('PlaceSearch插件加载成功')
    })
  } catch (error) {
    console.error('地图插件初始化失败:', error)
    ElMessage.error('地图插件初始化失败: ' + error.message)
  }
}

// 处理地图左键点击
const handleMapClick = async (e) => {
  if (isSettingStart) {
    const lnglat = e.lnglat;
    if (mapContainer.value) {
      const startPoint = mapContainer.value.addStartMarker(lnglat.lng, lnglat.lat);

      // 获取地址信息
      const address = await getAddressFromLngLat({lng: lnglat.lng, lat: lnglat.lat});
      startPointInfo.value = {
        lng: startPoint.lng,
        lat: startPoint.lat,
        address: address
      };

      isSettingStart = false;

      // 如果目的地也已设置，则自动规划路线
      if (destinationPointInfo.value) {
        await planRoute();
      }
    }
  }
}

// 处理地图右键点击
const handleMapRightClick = async (e) => {
  if (isSettingDestination) {
    const lnglat = e.lnglat;
    if (mapContainer.value) {
      const destinationPoint = mapContainer.value.addDestinationMarker(lnglat.lng, lnglat.lat);

      // 获取地址信息
      const address = await getAddressFromLngLat({lng: lnglat.lng, lat: lnglat.lat});
      destinationPointInfo.value = {
        lng: destinationPoint.lng,
        lat: destinationPoint.lat,
        address: address
      };

      isSettingDestination = false;

      // 如果起点也已设置，则自动规划路线
      if (startPointInfo.value) {
        await planRoute();
      }
    }
  }
}

// 规划路线
const planRoute = async () => {
  try {
    const result = await mapContainer.value.planDrivingRoute(
        {lng: startPointInfo.value.lng, lat: startPointInfo.value.lat},
        {lng: destinationPointInfo.value.lng, lat: destinationPointInfo.value.lat}
    );

    // 使用高德地图返回的路线距离
    if (result.routes && result.routes.length > 0) {
      const route = result.routes[0];
      const distance = (route.distance / 1000).toFixed(1); // 转换为公里并保留一位小数

      // 计算预计时间（假设平均速度30公里/小时）
      const time = Math.round((distance / 30) * 60);

      // 经济型计费（起步价13元，3公里内，超出部分2.3元/公里）
      const basePrice = 13;
      const perKmPrice = 2.3;
      const price = distance <= 3
          ? basePrice
          : (basePrice + (distance - 3) * perKmPrice).toFixed(0);

      routeInfo.value = {
        distance: distance,
        time: time,
        price: price
      };
    }

  } catch (error) {
    console.error('路线规划失败:', error);
    ElMessage.error('路线规划失败: ' + error.message);
  }
}

// 设置通过点击地图设置起点
const setStartByClick = () => {
  isSettingStart = true;
  isSettingDestination = false;
  ElMessage.info('请在地图上左键点击设置起点位置');
}

// 设置通过点击地图设置目的地
const setDestinationByClick = () => {
  isSettingDestination = true;
  isSettingStart = false;
  ElMessage.info('请在地图上右键点击设置目的地位置');
}

// 清除起点标记
const clearStartMarker = () => {
  if (mapContainer.value) {
    mapContainer.value.clearStartMarker();
    startPointInfo.value = null;
    routeInfo.value = null;
  }
}

// 清除目的地标记
const clearDestinationMarker = () => {
  if (mapContainer.value) {
    mapContainer.value.clearDestinationMarker();
    destinationPointInfo.value = null;
    routeInfo.value = null;
  }
}

// 清除所有标记
const clearAllMarkers = () => {
  if (mapContainer.value) {
    mapContainer.value.clearMarkers()
    startPointInfo.value = null
    destinationPointInfo.value = null
    routeInfo.value = null;
    isSettingStart = false;
    isSettingDestination = false;
  }
}

// 搜索地点
const searchPlace = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  if (!placeSearch) {
    ElMessage.error('搜索服务未加载完成')
    return
  }

  searching.value = true
  poiList.value = []

  placeSearch.search(searchKeyword.value, (status, result) => {
    searching.value = false

    if (status === 'complete' && result.info === 'OK' && result.poiList && result.poiList.pois) {
      ElMessage.success(`找到 ${result.poiList.pois.length} 个结果`)
      poiList.value = result.poiList.pois.slice(0, 10)
    } else {
      ElMessage.error('搜索失败，请重试')
    }
  })
}

// 选择POI
const selectPoi = (poi) => {
  if (!poi.location) {
    ElMessage.warning('该地点没有坐标信息')
    return
  }

  // 设置地图中心点
  map.setCenter([poi.location.lng, poi.location.lat])
  map.setZoom(16)

  // 清空搜索结果
  poiList.value = []
  searchKeyword.value = poi.name
}

// 展示轨迹动画
const showTrackAnimation = async () => {
  try {
    isAnimating.value = true;
    await mapContainer.value.startTrackAnimation();
    /*ElMessage.success('行程1已完成');*/
  } catch (error) {
    ElMessage.error('轨迹动画展示失败: ' + error.message);
  } finally {
    isAnimating.value = false;
  }
}

// 逆地理编码获取地址
const getAddressFromLngLat = (point) => {
  return new Promise((resolve) => {
    if (!geocoder) {
      window.AMap.plugin('AMap.Geocoder', () => {
        geocoder = new window.AMap.Geocoder()
        geocoder.getAddress([point.lng, point.lat], (status, result) => {
          if (status === 'complete' && result.regeocode) {
            resolve(result.regeocode.formattedAddress)
          } else {
            resolve('地址解析失败')
          }
        })
      })
    } else {
      geocoder.getAddress([point.lng, point.lat], (status, result) => {
        if (status === 'complete' && result.regeocode) {
          resolve(result.regeocode.formattedAddress)
        } else {
          resolve('地址解析失败')
        }
      })
    }
  })
}

// 组件挂载后初始化地图插件
onMounted(() => {
  initMapPlugins()
})
</script>

<style scoped>
.main-container {
  display: flex;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.map-section {
  flex: 1;
  height: 100%;
  position: relative;
}

.control-panel {
  width: 350px;
  height: 100%;
  background: white;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.panel-header {
  padding: 20px;
  background: linear-gradient(135deg, #0e88eb 100%, #ffffff 100%);
  color: white;
  flex-shrink: 0;
}

.panel-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  text-align: center;
}

.panel-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.control-group {
  margin-bottom: 25px;
}

.control-group h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #303133;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}

.input-group .el-input {
  width: 100%;
}

.point-actions .el-button {
  margin-bottom: 5px;
}

.point-info {
  margin-top: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.point-info p {
  margin: 5px 0;
}

.route-info {
  margin-top: 15px;
  padding: 10px;
  background: #e6f7ff;
  border-radius: 4px;
  font-size: 14px;
  border-left: 4px solid #1890ff;
}

.route-info p {
  margin: 5px 0;
}

.poi-list {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.poi-item {
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.poi-item:hover {
  background-color: #f5f7fa;
}

.poi-item:last-child {
  border-bottom: none;
}

.poi-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.poi-address {
  font-size: 12px;
  color: #666;
}

/* 滚动条样式 */
.poi-list::-webkit-scrollbar {
  width: 6px;
}

.poi-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.poi-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.poi-list::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-container {
    flex-direction: column;
  }

  .map-section {
    height: 60vh;
  }

  .control-panel {
    width: 100%;
    height: 40vh;
  }
}
</style>
